package com.tjetc.impl;

import com.tjetc.dao.MaintenancerequestMapper;
import com.tjetc.domian.Maintenancerequest;
import com.tjetc.service.MaintenanceService;
import com.tjetc.utils.Db;
import com.tjetc.vo.Result;

import java.util.List;

public class MaintenanceServiceImpl implements MaintenanceService {
    private MaintenancerequestMapper maintenanceMapper= Db.getMapper(MaintenancerequestMapper.class);
    @Override
    public Result add(Maintenancerequest maintenancerequest) {
        try {
            Db.start();
            if (maintenancerequest.getResidentid() != null) {
                List<Maintenancerequest> existingRequests = maintenanceMapper.selectByRid(maintenancerequest.getResidentid());
                if (!existingRequests.isEmpty()) {
                    for (Maintenancerequest existingRequest : existingRequests) {
                        if (maintenancerequest.equals(existingRequest)) {

                            return new Result(500, "该用户已经申请过维修", null);
                        }
                    }
                }

            int rows = maintenanceMapper.insertSelective(maintenancerequest);
            Db.commit();
            return rows == 1 ? new Result(200, "添加成功", maintenancerequest) : new Result(500, "添加失败", null);
            }
        } catch (Exception e) {
            Db.rollback();
            throw new RuntimeException(e);
        } finally {
            Db.close();
        }
        return new Result(500, "ResidentID不能为空", null);
    }

    @Override
    public List<Maintenancerequest> select(int residentid) {
        if (maintenanceMapper.select(residentid)!=null){
            return maintenanceMapper.select(residentid);
        }
        return null;
    }

    @Override
    public List<Maintenancerequest> selectAll() {
        return maintenanceMapper.selectAll();
    }

    @Override
    public Result update(int requestid,String status) {
        try {
            Db.start();
            if (requestid != 0) {
                Maintenancerequest maintenancerequest = maintenanceMapper.selectByPrimaryKey(requestid);
                if (maintenancerequest != null) {
                    maintenancerequest.setStatus(status);
                    int rows = maintenanceMapper.updateByrequestId(maintenancerequest);
                    Db.commit();
                    return rows == 1 ? new Result(200, "修改成功", maintenancerequest) : new Result(500, "修改失败", null);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            Db.rollback();
        }finally {
            Db.close();
        }
        return new Result(500, "修改失败", null);
    }
}